// pages/listeningDetail/listeningDetail.js
let util = require("../../utils/util.js");
let WxParse = require('../../wxParse/wxParse.js');
const innerAudioContext = wx.createInnerAudioContext();
// const innerAudioContext = wx.getBackgroundAudioManager();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        audioCtx: "",
        progress: 20,//进度条进度
        audioSrc:"",
        curTimeVal: "00:00",
        endTime:"00:00",
        runTime:0,
        isPlayed:false,
        isFirst:true,//是不是第一次播放,
        bookId:'',
        detail:{},
        audioList:[],
        bookList:[],
        commentList:[],
        pageNumber:1,
        readMoreFlag: false,
        playindex:0,
        bookImg:'',
        endTime:0,
        myPublish:'',
        hiddenDetailFlag:true,//是否收起书籍详情 true-显示  false-收起
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.playAudio();
        this.setData({
            bookId:options.id
        });
        this.getDetail();
    },
    //获取书籍详情
    getDetail:function(){
        var that = this;
        var userInfo = JSON.parse(wx.getStorageSync("userInfo")).smAdmin.id;
        var bookId = this.data.bookId;
        util.wxAjax("glBook/detail", "post", {
            id: bookId,
            adminid: userInfo
        }, function (res) {
            var data = res.data;
            if (data.result == 200){
                wx.hideNavigationBarLoading();
                wx.stopPullDownRefresh();
                wx.hideLoading();
                WxParse.wxParse('article1', 'html',  data.data.glBook.about, that, 0);
                that.setData({
                    detail: data.data,
                    audioSrc: data.data.sections[0].sectionUrl,
                    audioList: data.data.sections,
                    bookList: data.data.glBook,
                    commentList: data.data.commentList,
                    readMoreFlag: data.data.commentList.length > 19 ? true : false
                })
                that.playAudio();
            }
        })
    },
    bookmoreCommon: function(){
        let bookId = this.data.bookId;
        let adminid = JSON.parse(wx.getStorageSync("userInfo")).smAdmin.id;
        let commentList = this.data.commentList;
        let pageNum = this.data.pageNumber;
        var that = this;
        util.wxAjax("glBook/bookmoreCommon","post",{
            id: bookId,
            adminid: adminid,
            pageNum: pageNum
        },function(res){
            var data = res.data;
            if (!!data.data){
                wx.hideNavigationBarLoading();
                wx.stopPullDownRefresh();
                wx.hideLoading();
                commentList = commentList.concat(data.data);
                that.setData({
                    commentList: commentList
                });
            }else{
                wx.hideNavigationBarLoading();
                wx.stopPullDownRefresh();
                wx.hideLoading();
            }
        });
    },
    //上拉刷新
    onPullDownRefresh: function () {
        // 显示顶部刷新图标  
        wx.showNavigationBarLoading();
        this.setData({
            pageNumber: 1,
            commentList:[]
        });
        this.getDetail();
    },
    //下拉加载
    onReachBottom: function () {
        var flag = this.data.readMoreFlag;
        if (flag) {
            var pageNum1 = this.data.pageNumber;
            // 显示加载图标  
            wx.showLoading({
                title: '玩命加载中',
            })
            this.setData({
                pageNumber: ++pageNum1,
            });
            this.bookmoreCommon();
        }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        console.log(innerAudioContext);
    },
    onUnload:function(){
        // innerAudioContext.stop();
    },
    //播放音乐
    playAudio: function () {
        var that = this;
        let src = this.data.audioSrc;
        innerAudioContext.src = src;
        innerAudioContext.stop();
    },
    play: function (e) {
        wx.showLoading({
            title: '加载中....',
        })
        var that = this;
        innerAudioContext.play();
        innerAudioContext.onPlay(() => {
            wx.hideLoading();
            var isPlayed = this.data.isPlayed;
            var isFirst = this.data.isFirst;
            that.updateTime(that);
            if (!isPlayed) {
                if(isFirst){
                    innerAudioContext.pause();
                    innerAudioContext.play();
                    that.setData({
                        isFirst:false
                    });
                }
                that.setData({
                    isPlayed: true,
                });
            }
        });
    },
    pause: function () {
        innerAudioContext.pause();
        this.setData({
            isPlayed:false
        });
    },
    updateTime: function (that) {
        innerAudioContext.onTimeUpdate((res) => {
            //更新时把当前的值给slide组件里的value值。slide的滑块就能实现同步更新
            that.setData({
                duration: innerAudioContext.duration.toFixed(2) * 100,
                curTimeVal: that.changeTime(innerAudioContext.currentTime.toFixed(2)),
                runTime: innerAudioContext.currentTime.toFixed(2) *100,
                endTime: this.changeTime(innerAudioContext.duration.toFixed(2))
            })
        })
        //播放到最后一秒
        if (innerAudioContext.duration.toFixed(2) - innerAudioContext.currentTime.toFixed(2) <= 0) {
            that.setStopState(that)
        }
        innerAudioContext.onEnded(() => {
            that.setStopState(that)
        })
    },
    //拖动滑块
    slideBar: function (e) {
        let that = this;
        var curval = e.detail.value; //滑块拖动的当前值
        console.log(curval);
        innerAudioContext.seek(Math.floor(curval/100)); //让滑块跳转至指定位置
        innerAudioContext.onSeeked((res) => {
            this.updateTime(that) //注意这里要继续出发updataTime事件，
        });
    },
    setStopState: function (that) {
        that.setData({
            curTimeVal: "00:00",
            isPlayed:false
        })
        innerAudioContext.stop();
    },
    //将秒数变成时间
    changeTime:function(time){
        var minute = Math.floor(time / 60) < 10 ? "0" + Math.floor(time / 60) : Math.floor(time / 60);
        var second = Math.ceil(time % 60) < 10 ? "0" + Math.ceil(time % 60) : Math.ceil(time % 60);
        return minute+":"+second;
    },
    //点击章节列表开始播放
    start_play:function(e){
        console.log(e)
        innerAudioContext.stop();
        var index = e.currentTarget.dataset.index;
        var msg = e.currentTarget.dataset.msg;
        var endtime = this.changeTime(msg.sectionSec);
        this.setData({
            playindex: index,
            audioSrc: msg.sectionUrl,
            endTime: endtime
        });
        this.playAudio();
        this.play();
    },
    //播放上一首
    preAudio:function(){
        if (this.data.playindex > 0){
            innerAudioContext.stop();
            var index = --this.data.playindex;
            this.setData({
                playindex: index,
                audioSrc: this.data.audioList[index].sectionUrl
            });
            this.playAudio();
            this.play();
        }else{
            wx.showToast({
                title: '已经是第一章了~',
                icon:"none"
            })
        }
    },
    //播放下一首
    nextAudio:function(){
        var index = this.data.playindex;
        var length = this.data.audioList.length;
        console.log(length);
        if(index < --length){
            index = ++index;
            this.setData({
                playindex: index,
                audioSrc: this.data.audioList[index].sectionUrl
            });
            this.playAudio();
            this.play();
        }else{
            wx.showToast({
                title: '已经是最后一章了~',
                icon: "none"
            })
        }
    },
    //发表评论
    publish:function(){
        if(this.data.myPublish){
            var userInfo = JSON.parse(wx.getStorageSync("userInfo")).smAdmin.id;
            var that = this;
            var commentList = this.data.commentList;
            util.wxAjax("glBook/updateCommentsAddOne", "post", {
                id: that.data.bookId,
                adminid: userInfo,
                content: that.data.myPublish
            }, function (res) {
                var data = res.data;
                var temp = [];
                if (data.result == 200 || data.result == "200") {
                    that.getDetail();
                    that.setData({
                        myPublish:""
                    });
                }else{
                    wx.showToast({
                        title: '评论失败！',
                        icon: 'none'
                    })
                }
            })
        }else{
            wx.showToast({
                title: '请输入评论信息！',
                icon:"none"
            });
        }
    },
    //获取留言板的内容
    getTextArea:function(e){
        var value = e.detail.value;
        this.setData({
            myPublish: value
        })
    },
    //收起书籍详情
    hiddenDetail:function(){
        var hiddenDetailFlag = this.data.hiddenDetailFlag;
        this.setData({
            hiddenDetailFlag: !hiddenDetailFlag
        });
    },
    //书籍点赞
    dianzan:function(){
        var that = this;
        var bookList = this.data.bookList;
        var userInfo = JSON.parse(wx.getStorageSync("userInfo"));
        util.wxAjax("glBook/updateBookLaudsAddOne","post",{
            adminid:userInfo.smAdmin.id,
            id:bookList.id
        },function(res){
            var data = res.data;
            if(data.result == 200 || data.reslut == "200"){
                wx.showToast({
                    title: '点赞成功！',
                })
                bookList.lauds = data.data;
                bookList.isLauds = 1;
                that.setData({
                    bookList: bookList
                });
            }else{
                wx.showToast({
                    title: data.msg,
                    icon:"none"
                })
            }
        });
    },
    //评论点赞
    pinglunDianzan:function(options){
        var that = this;
        var books = this.data.bookList;
        var userInfo = JSON.parse(wx.getStorageSync("userInfo"));
        var id = options.currentTarget.dataset.id;
        var index = options.currentTarget.dataset.index;
        var commentList = this.data.commentList;
        util.wxAjax("glBook/updateLaudsAddOne","post",{
            contentId: books.id,
            adminid:userInfo.smAdmin.id,
            id:id
        },function(res){
            var data = res.data;
            if(data.reslut == 200 || data.result == "200"){
                commentList[index].lauds += 1;
                commentList[index].isLauds = 1;
                that.setData({
                    commentList: commentList
                });
            }else{
                wx.showToast({
                    title: data.msg,
                    icon:"none"
                })
            }
        });
    }
})